package io.kiki.sba.registry.client.util;

import io.kiki.sba.registry.client.api.ClientConfig;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Map.Entry;


public class HttpClientUtils {
    private static final char AND = '&';


    public static String get(String url, Map<String, String> params, ClientConfig clientConfig) throws Exception {
        HttpURLConnection httpURLConnection = create(getFullPath(url, params), clientConfig);
        httpURLConnection.setRequestMethod("GET");

        BufferedReader bufferedReader = null;
        try {
            StringBuilder sb = new StringBuilder();

            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                String contentEncoding = httpURLConnection.getContentEncoding();
                if (contentEncoding != null) {
                    bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), contentEncoding));
                } else {
                    bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                }

                String string;
                while ((string = bufferedReader.readLine()) != null) {
                    sb.append(string).append("\n");
                }
                if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '\n') {
                    sb.deleteCharAt(sb.length() - 1);
                }

                return sb.toString();
            }
        } finally {
            httpURLConnection.disconnect();
            if (null != bufferedReader) {
                bufferedReader.close();
            }
        }
        return null;
    }


    private static HttpURLConnection create(String httpUrl, ClientConfig clientConfig) throws Exception {
        URL url = new URL(httpUrl);
        URLConnection urlConnection = url.openConnection();
        HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
        httpConnection.setDoOutput(true);
        httpConnection.setDoInput(true);
        httpConnection.setUseCaches(false);
        httpConnection.setRequestProperty("Content-type", "text/plain");
        httpConnection.setConnectTimeout(clientConfig.getConnectTimeout());
        httpConnection.setReadTimeout(clientConfig.getSocketTimeout());
        return httpConnection;
    }

    private static String getFullPath(String url, Map<String, String> params) {
        StringBuilder sb = new StringBuilder(url);
        if (params != null) {
            sb.append("?");
            for (Entry<String, String> param : params.entrySet()) {
                sb.append(param.getKey());
                sb.append("=");
                sb.append(param.getValue());
                sb.append("&");
            }
            if (sb.charAt(sb.length() - 1) == AND) {
                sb.deleteCharAt(sb.length() - 1);
            }
        }
        return sb.toString();
    }
}
